package com.yizhilu.os.edu.controller.kuaijidao;

import com.yizhilu.os.common.util.SystemUtil;
import com.yizhilu.os.core.entity.PageEntity;
import com.yizhilu.os.core.service.cache.MemCache;
import com.yizhilu.os.core.util.MD5;
import com.yizhilu.os.core.util.ObjectUtils;
import com.yizhilu.os.core.util.Security.Base64;
import com.yizhilu.os.edu.common.EduBaseController;
import com.yizhilu.os.edu.constants.enums.CourseProfileType;
import com.yizhilu.os.edu.constants.enums.SellType;
import com.yizhilu.os.edu.constants.enums.WebSiteProfileType;
import com.yizhilu.os.edu.entity.course.Course;
import com.yizhilu.os.edu.entity.course.CourseDto;
import com.yizhilu.os.edu.entity.course.CourseKpoint;
import com.yizhilu.os.edu.entity.course.CourseProfile;
import com.yizhilu.os.edu.entity.course.QueryCourse;
import com.yizhilu.os.edu.entity.course.Teacher;
import com.yizhilu.os.edu.entity.member.MemberType;
import com.yizhilu.os.edu.entity.user.UserExpandDto;
import com.yizhilu.os.edu.service.article.ArticleService;
import com.yizhilu.os.edu.service.course.CourseFavoritesService;
import com.yizhilu.os.edu.service.course.CourseKpointService;
import com.yizhilu.os.edu.service.course.CourseLiveKpointService;
import com.yizhilu.os.edu.service.course.CourseProfileService;
import com.yizhilu.os.edu.service.course.CourseService;
import com.yizhilu.os.edu.service.course.TeacherService;
import com.yizhilu.os.edu.service.kuaijidao.UserKuaijiDaoService;
import com.yizhilu.os.edu.service.member.MemberRecordService;
import com.yizhilu.os.edu.service.member.MemberTypeService;
import com.yizhilu.os.edu.service.order.TrxorderDetailService;
import com.yizhilu.os.edu.service.order.TrxorderService;
import com.yizhilu.os.edu.service.user.UserService;
import com.yizhilu.os.edu.service.website.WebsiteProfileService;
import com.yizhilu.os.sysuser.entity.QuerySubject;
import com.yizhilu.os.sysuser.entity.Subject;
import com.yizhilu.os.sysuser.service.SubjectService;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping({"/kuaijidao"})
public class CourseH5Controller extends EduBaseController {
    private static final Logger logger = LoggerFactory.getLogger(CourseH5Controller.class);
    MemCache memcache = MemCache.getInstance();
    private static final String showCourseList = getViewPath("/course/courses-list");
    private static final String showlivelist = getViewPath("/course/courses-live-list");
    private static final String couinfo = getViewPath("/course/course-infor");
    private static final String couLiveinfo = getViewPath("/course/course-live-infor");
    private static final String showPublicCourseList = getViewPath("/course/publicCourses-list");
    private static final String live_play = getViewPath("/course/live_play");
    private static final String courses_ajax = getViewPath("/course/courses_ajax");
    private static final String uc_mycourse = getViewPath("/ucenter/mycourse");
    private static final String uc_live = getViewPath("/ucenter/uc_live");
    private String favouriteList = getViewPath("/ucenter/favourite_course_list");
    @Autowired
    private CourseService courseService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CourseKpointService courseKpointService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private TrxorderService trxorderService;
    @Autowired
    private CourseProfileService courseProfileService;
    @Autowired
    UserService userService;
    @Autowired
    private MemberTypeService memberTypeService;
    @Autowired
    private CourseFavoritesService courseFavoritesService;
    @Autowired
    private MemberRecordService memberRecordService;
    @Autowired
    private WebsiteProfileService websiteProfileService;
    @Autowired
    private CourseLiveKpointService courseLiveKpointService;
   

    @Autowired
    private TrxorderDetailService trxorderDetailService;

    public CourseH5Controller() {
    }

    @InitBinder({"queryCourse"})
    public void initBinderQueryCourse(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("queryCourse.");
    }

    @RequestMapping({"/front/showcoulist"})
    public ModelAndView showCourseList(HttpServletRequest request, @ModelAttribute("page") PageEntity page, @ModelAttribute("queryCourse") QueryCourse queryCourse) {
        ModelAndView modelAndView = new ModelAndView(showCourseList);

        try {
            page.setPageSize(12);
            queryCourse.setIsavaliable(Long.valueOf(0L));
            queryCourse.setSellType("NOLIVE");
            List e = this.courseService.getCourseListPage(queryCourse, page);
            QuerySubject querySubject = new QuerySubject();
            querySubject.setParentId(Long.valueOf(0L));
            List subjectList = this.subjectService.getSubjectListByLevel(querySubject);
            List teacherList;
            if(ObjectUtils.isNotNull(queryCourse.getSubjectId())) {
                Subject teacher = new Subject();
                teacher.setSubjectId(queryCourse.getSubjectId());
                teacher = this.subjectService.getSubjectBySubjectId(teacher);
                modelAndView.addObject("subject", teacher);
                teacherList = null;
                if(teacher.getParentId().longValue() != 0L) {
                    teacherList = this.subjectService.getSubjectListByOne(teacher.getParentId());
                } else {
                    teacherList = this.subjectService.getSubjectListByOne(teacher.getSubjectId());
                }

                modelAndView.addObject("sonSubjectList", teacherList);
            }

            Teacher teacher1 = this.teacherService.getTeacherById(queryCourse.getTeacherId());
            modelAndView.addObject("teacher", teacher1);
            teacherList = this.teacherService.getTeacherList(new Teacher());
            modelAndView.addObject("courseList", e);
            modelAndView.addObject("page", page);
            modelAndView.addObject("course", queryCourse);
            modelAndView.addObject("teacherList", teacherList);
            modelAndView.addObject("subjectList", subjectList);
            Map saleMap = this.websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.sale.toString());
            modelAndView.addObject("saleMap", saleMap);
            MemberType memberType = this.memberTypeService.getMemberTypeById(queryCourse.getMembertype());
            modelAndView.addObject("memberType", memberType);
            List memberTypes = this.memberTypeService.getWebMemberTypes();
            modelAndView.addObject("memberTypes", memberTypes);
            if(ObjectUtils.isNotNull(queryCourse.getTeacherId())) {
                modelAndView.addObject("teacher", this.teacherService.getTeacherById(queryCourse.getTeacherId()));
            }

            return modelAndView;
        } catch (Exception var13) {
            logger.error("CourseController.showCourseList", var13);
            return new ModelAndView(this.setExceptionRequest(request, var13));
        }
    }

    @RequestMapping({"/front/showPublicCourselist"})
    public ModelAndView showPublicCourseList(HttpServletRequest request, @ModelAttribute("page") PageEntity page, @ModelAttribute("queryCourse") QueryCourse queryCourse) {
        ModelAndView modelAndView = new ModelAndView(showPublicCourseList);

        try {
            page.setPageSize(12);
            queryCourse.setIsavaliable(Long.valueOf(0L));
            queryCourse.setSellType("NOLIVE");
            List e = this.courseService.getPublicCourseListPage(queryCourse, page);
            QuerySubject querySubject = new QuerySubject();
            querySubject.setParentId(Long.valueOf(0L));
            List subjectList = this.subjectService.getSubjectListByLevel(querySubject);
            List teacherList;
            if(ObjectUtils.isNotNull(queryCourse.getSubjectId())) {
                Subject teacher = new Subject();
                teacher.setSubjectId(queryCourse.getSubjectId());
                teacher = this.subjectService.getSubjectBySubjectId(teacher);
                modelAndView.addObject("subject", teacher);
                teacherList = null;
                if(teacher.getParentId().longValue() != 0L) {
                    teacherList = this.subjectService.getSubjectListByOne(teacher.getParentId());
                } else {
                    teacherList = this.subjectService.getSubjectListByOne(teacher.getSubjectId());
                }

                modelAndView.addObject("sonSubjectList", teacherList);
            }

            Teacher teacher1 = this.teacherService.getTeacherById(queryCourse.getTeacherId());
            modelAndView.addObject("teacher", teacher1);
            teacherList = this.teacherService.getTeacherList(new Teacher());
            modelAndView.addObject("publicCourseList", e);
            modelAndView.addObject("page", page);
            modelAndView.addObject("course", queryCourse);
            modelAndView.addObject("teacherList", teacherList);
            modelAndView.addObject("subjectList", subjectList);
            Map saleMap = this.websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.sale.toString());
            modelAndView.addObject("saleMap", saleMap);
            MemberType memberType = this.memberTypeService.getMemberTypeById(queryCourse.getMembertype());
            modelAndView.addObject("memberType", memberType);
            List memberTypes = this.memberTypeService.getWebMemberTypes();
            modelAndView.addObject("memberTypes", memberTypes);
            if(ObjectUtils.isNotNull(queryCourse.getTeacherId())) {
                modelAndView.addObject("teacher", this.teacherService.getTeacherById(queryCourse.getTeacherId()));
            }

            return modelAndView;
        } catch (Exception var13) {
            logger.error("CourseController.showCourseList", var13);
            return new ModelAndView(this.setExceptionRequest(request, var13));
        }
    }

    @RequestMapping({"/front/showlivelist"})
    public ModelAndView showlivelist(HttpServletRequest request, @ModelAttribute("page") PageEntity page, @ModelAttribute("queryCourse") QueryCourse queryCourse) {
        ModelAndView modelAndView = new ModelAndView(showlivelist);

        try {
            page.setPageSize(6);
            queryCourse.setIsavaliable(Long.valueOf(0L));
            queryCourse.setSellType(SellType.LIVE.toString());
            List e = this.courseLiveKpointService.getCourseLiveListForFront(queryCourse, page);
            QuerySubject querySubject = new QuerySubject();
            querySubject.setParentId(Long.valueOf(0L));
            List subjectList = this.subjectService.getSubjectListByLevel(querySubject);
            if(ObjectUtils.isNotNull(queryCourse.getSubjectId())) {
                Subject saleMap = new Subject();
                saleMap.setSubjectId(queryCourse.getSubjectId());
                saleMap = this.subjectService.getSubjectBySubjectId(saleMap);
                modelAndView.addObject("subject", saleMap);
                if(ObjectUtils.isNotNull(saleMap)) {
                    List sonSubjectList = null;
                    if(saleMap.getParentId().longValue() != 0L) {
                        sonSubjectList = this.subjectService.getSubjectListByOne(saleMap.getParentId());
                    } else {
                        sonSubjectList = this.subjectService.getSubjectListByOne(saleMap.getSubjectId());
                    }

                    modelAndView.addObject("sonSubjectList", sonSubjectList);
                }
            }

            modelAndView.addObject("courseList", e);
            modelAndView.addObject("page", page);
            modelAndView.addObject("course", queryCourse);
            modelAndView.addObject("subjectList", subjectList);
            Map saleMap1 = this.websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.sale.toString());
            modelAndView.addObject("saleMap", saleMap1);
            return modelAndView;
        } catch (Exception var10) {
            logger.error("CourseController.showCourseList", var10);
            return new ModelAndView(this.setExceptionRequest(request, var10));
        }
    }

    @RequestMapping({"/front/couinfo/{id}"})
    public String couinfo(Model model, HttpServletRequest request, @PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        try {
            CourseDto e = this.courseService.getCourseInfoById(id);
            List userExpandList = this.courseService.queryUserExpandListByCourseId(id);
            if(ObjectUtils.isNull(e)) {
                redirectAttributes.addAttribute("msg", "对不起该课程已经下架或者删除");
                return "redirect:/front/success";
            }

            List memberTypes = this.memberTypeService.getMemberTypesBycourse(e.getId());
            e.setMemberTypes(memberTypes);
            List articleListOrderclickTimes = this.articleService.queryArticleListOrderclickTimes(10);
            List courseList = this.courseService.getSubjectCourseList((Long)null, e.getId(), 3, e.getSellType());
            boolean isok = false;
            boolean isok1 = this.trxorderService.checkCourseLook(id, getLoginUserId(request));
            boolean isok2 = false;
            if(!isok1) {
                isok2 = this.memberRecordService.checkUserMember(getLoginUserId(request), e.getId());
            }

            if(isok1 || isok2) {
                isok = true;
            }

            Object courseDtos = new ArrayList();
            if(e.getSellType().equalsIgnoreCase(SellType.PACKAGE.toString())) {
                ArrayList liveKpointList = new ArrayList();
                liveKpointList.add(e.getId());
                courseDtos = this.courseService.getCourseListPackage(liveKpointList);
                if(ObjectUtils.isNotNull((List)courseDtos)) {
                    model.addAttribute("currentCourseId", ((CourseDto)((List)courseDtos).get(0)).getId());
                }
            } else {
                ((List)courseDtos).add(e);
                model.addAttribute("currentCourseId", e.getId());
            }

            model.addAttribute("coursePackageList", courseDtos);
            model.addAttribute("courseList", courseList);
            model.addAttribute("course", e);
            model.addAttribute("articleListOrderclickTimes", articleListOrderclickTimes);
            model.addAttribute("isok", Boolean.valueOf(isok));
            model.addAttribute("userExpandList", userExpandList);
            this.courseProfileService.updateCourseProfile(CourseProfileType.viewcount.toString(), e.getId(), Long.valueOf(1L), CourseProfile.ADD);
            if(SellType.LIVE.toString().equals(e.getSellType())) {
                List liveKpointList1 = this.courseLiveKpointService.getCourseLiveKpointByCourseId(id);
                model.addAttribute("liveKpointList", liveKpointList1);
                return couLiveinfo;
            }
        } catch (Exception var15) {
            logger.error("CourseController.couinfo", var15);
            return this.setExceptionRequest(request, var15);
        }

        return couinfo;
    }

    @RequestMapping({"/front/coursetree/{id}"})
    @ResponseBody
    public Object getCourseTree(@PathVariable Long id) {
        Map json = null;
        CourseKpoint courseKpoint = new CourseKpoint();
        courseKpoint.setCourseId(id);
        List courseKpointList = this.courseKpointService.getCourseKpointList(courseKpoint);
        json = this.getJsonMap(true, "", courseKpointList);
        return json;
    }

    @RequestMapping({"/front/ajax/course"})
    public ModelAndView ajaxcourse(HttpServletRequest request, Model model, Long subjectId, String sellType) {
        ModelAndView modelAndView = new ModelAndView(courses_ajax);

        try {
            List e = this.courseService.getSubjectCourseList(subjectId, (Long)null, 8, sellType);
            model.addAttribute("courseList", e);
            return modelAndView;
        } catch (Exception var7) {
            logger.error("CourseController.showCourseList", var7);
            return new ModelAndView(this.setExceptionRequest(request, var7));
        }
    }

    @RequestMapping({"/getUserCourse"})
    @ResponseBody
    public Map<String, Object> userCourse(HttpServletRequest request,HttpServletResponse response) {
        Map dataMap = new LinkedHashMap<String,Object>();
        try {
            List courseDtos = this.courseService.getUserBuyCourseList(getLoginUserId(request));
            List details = this.trxorderDetailService.getTrxorderDetailListBuy(Long.valueOf(request.getParameter("id")));
            List coursezhibo = this.courseService.getUserBuyLiveCourseList(getLoginUserId(request));
            dataMap.put("courseLives", details);
            dataMap.put("buycourses", details);
            System.out.print(coursezhibo.size()+"++++++test+++++++"+courseDtos.size());

        } catch (Exception var7) {
            var7.printStackTrace();
            return SystemUtil.buildResultMap(1, dataMap, "参数输入异常");
        }

        return dataMap;
    }

    @RequestMapping({"/uc/mylive"})
    public String myLive(Model model, HttpServletRequest request) {
        try {
            List e = this.courseService.getUserBuyCourseList(getLoginUserId(request));
            List courseDtos = this.courseService.getUserBuyLiveCourseList(getLoginUserId(request));
            Map mapCourseList = this.courseService.getCourseListByHomePage(Long.valueOf(0L));
            model.addAttribute("courses", e);
            model.addAttribute("buycourses", courseDtos);
            model.addAttribute("mapCourseList", mapCourseList);
        } catch (Exception var6) {
            return this.setExceptionRequest(request, var6);
        }

        return uc_live;
    }

    @RequestMapping({"/course/check/{id}"})
    @ResponseBody
    public Map<String, Object> checkCourse(@PathVariable Long id, HttpServletRequest request) {
        Map json = null;

        try {
            Course e = this.courseService.getCourseById(id);
            if(e.getIsavaliable().longValue() != 0L) {
                json = this.getJsonMap(false, "课程已下架", (Object)null);
            } else if(e.getCurrentprice().doubleValue() <= 0.0D) {
                json = this.getJsonMap(false, "开通课程金额不能为0", (Object)null);
            } else {
                json = this.getJsonMap(true, "true", (Object)null);
            }
        } catch (Exception var5) {
            logger.error("CourseController.checkCourse", var5);
            json = this.getJsonMap(false, "error", (Object)null);
        }

        return json;
    }

    @RequestMapping({"/uc/fav"})
    public ModelAndView favouriteCourseList(HttpServletRequest request, @ModelAttribute("page") PageEntity page) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(this.favouriteList);

        try {
            List e = this.courseFavoritesService.getFavouriteCourseDTO(getLoginUserId(request), page);
            List courseMoreList = this.courseFavoritesService.getMoreFavouriteCourse();
            Map mapCourseList = this.courseService.getCourseListByHomePage(Long.valueOf(0L));
            modelAndView.addObject("courseList", e);
            modelAndView.addObject("courseMoreList", courseMoreList);
            modelAndView.addObject("mapCourseList", mapCourseList);
            modelAndView.addObject("page", page);
            return modelAndView;
        } catch (Exception var7) {
            var7.printStackTrace();
            logger.error("favouriteCourseList" + var7);
            return new ModelAndView(this.setExceptionRequest(request, var7));
        }
    }

    @RequestMapping({"/uc/del"})
    public ModelAndView delCourseFav(HttpServletRequest request, @RequestParam("sellIdArr") String courseIds) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/uc/fav");

        try {
            this.courseFavoritesService.deleteCourseFavoritesById(courseIds);
            return modelAndView;
        } catch (Exception var5) {
            var5.printStackTrace();
            return new ModelAndView(this.setExceptionRequest(request, var5));
        }
    }

    @RequestMapping({"/course/to/live"})
    public String toLive(@RequestParam("courseId") Long courseId, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String url = "";

        try {
            if(getLoginUserId(request).longValue() == 0L) {
                return "redirect:/login";
            }

            Course e = this.courseService.getCourseById(courseId);
            if(e == null) {
                redirectAttributes.addAttribute("msg", "对不起该课程已经下架或者删除");
                return "redirect:/front/success";
            }

            if(e.getIsavaliable().longValue() != 0L) {
                redirectAttributes.addAttribute("msg", "对不起该课程已经下架");
                return "redirect:/front/success";
            }

            boolean isok = false;
            boolean isok1 = this.trxorderService.checkCourseLook(courseId, getLoginUserId(request));
            boolean isok2 = false;
            if(!isok1) {
                isok2 = this.memberRecordService.checkUserMember(getLoginUserId(request), e.getId());
            }

            if(isok1 || isok2) {
                isok = true;
            }

            if(!isok && e.getIsPay() != 0) {
                redirectAttributes.addAttribute("msg", "请购买后观看");
                return "redirect:/front/success";
            }

            url = e.getFreeurl().trim();
            UserExpandDto userExpandDto = this.userService.queryUserExpand(getLoginUserId(request).longValue());
            String nickName = userExpandDto.getShowname();
            redirectAttributes.addAttribute("nickname", nickName);
            logger.info("----------------nickname----:" + nickName);
            String key;
            if(e.getLiveWord() != null && !e.getLiveWord().equals("")) {
                key = MD5.getMD5(e.getLiveWord());
                redirectAttributes.addAttribute("token", key);
                redirectAttributes.addAttribute("sec", "md5");
            }

            key = Base64.encode(userExpandDto.getId() + "");
            this.memcache.set(key, key, 60);
            redirectAttributes.addAttribute("k", key);
        } catch (Exception var12) {
            logger.error("CourseController.toLive", var12);
            return this.setExceptionRequest(request, var12);
        }

        return "redirect:" + url;
    }

    @RequestMapping({"/check/live"})
    public void liveCheck(HttpServletRequest request, HttpServletResponse response) {
        try {
            String e = request.getParameter("k");
            String keyVal = (String)this.memcache.get(e);
            if(keyVal != null) {
                response.getWriter().write("pass");
            } else {
                response.getWriter().write("fail");
            }
        } catch (Exception var5) {
            logger.error("CourseController.liveCheck", var5);
            this.setExceptionRequest(request, var5);
        }

    }

    @RequestMapping({"/course/to/free/live"})
    public String tofreeLive(@RequestParam("courseId") Long courseId, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String url = "";

        try {
            Course e = this.courseService.getCourseById(courseId);
            if(e == null) {
                redirectAttributes.addAttribute("msg", "对不起该课程已经下架或者删除");
                return "redirect:/front/success";
            }

            if(e.getIsavaliable().longValue() != 0L) {
                redirectAttributes.addAttribute("msg", "对不起该课程已经下架");
                return "redirect:/front/success";
            }

            url = e.getFreeurl().trim();
            redirectAttributes.addAttribute("nickname", "匿名");
            if(e.getLiveWord() != null && !e.getLiveWord().equals("")) {
                String s = MD5.getMD5(e.getLiveWord());
                redirectAttributes.addAttribute("token", s);
                redirectAttributes.addAttribute("sec", "md5");
            }

            SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String key = Base64.encode(s1.format(new Date()));
            this.memcache.set(key, key, 60);
            redirectAttributes.addAttribute("k", key);
        } catch (Exception var8) {
            logger.error("CourseController.tofreeLive", var8);
            return this.setExceptionRequest(request, var8);
        }

        return "redirect:" + url;
    }
}
